import { Avatar, message, Modal, Pagination, Table, TableProps } from "antd";
import QueryForm from "../../user/components/QueryForm";
import { User } from "@/types/system/user";
import { useCallback, useEffect, useState } from "react";
import { queryExcludeRoleUser, setAuthUser } from "@/api/system/role";
import { Role } from "@/types/system/role";

interface Props {
  isModalOpen: boolean;
  roleId: string;
  roleName: string;
  close?: () => void;
  change?: () => void;
}
type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];
export default function AuthUser(props: Props) {
  const [messageApi] = message.useMessage();
  const [userIds, setUserIds] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchForm, setSearchForm] = useState<User.Query>({
    userName: "",
    nickName: "",
    email: "",
    phonenumber: "",
    sex: "",
    type: "",
    // 账号状态（0正常 1停用
    status: "",
  });
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  const [tableData, setTableData] = useState<User.Row[]>([]);
  /**
   * 获取用户列表
   */
  const getUserList = useCallback(async () => {
    if (!props.roleId) return;
    const { nickName, email, phonenumber, sex, type, userName, status } =
      searchForm;
    const params = {
      nickName,
      email,
      phonenumber,
      sex,
      type,
      pageNo:pagination.pageNo,
      pageSize:pagination.pageSize,
      status,
      userName,
      excludeRoleId: props.roleId,
    };
    setLoading(true);
    const res = await queryExcludeRoleUser(params);
    setLoading(false);
    if (res.code === 200) {
      setTableData(res.data.rows || []);
      setPagination({
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        total: res.data.total || 0,
      });
    }
  }, [pagination.pageNo, pagination.pageSize, props.roleId, searchForm]);
  /**
   * 修改接口
   * @param data
   */
  const authInf = async (data: Role.AuthUser) => {
    try {
      setLoading(true);
      const res = await setAuthUser(data);
      setLoading(false);
      if (res.code === 200) {
        props.close && props.close();
        props.change && props.change();
        messageApi.success("授权成功");
      }
    } catch (error) {
      console.log(error);

      setLoading(false);
    }
  };
  /**
   * 校验函数
   */
  const handleOk = async () => {
    if (!userIds.length) {
      messageApi.warning("请选择");
      return;
    }
    const params = {
      roleId: props.roleId,
      userIdList: userIds,
    };
    authInf(params);
  };
  useEffect(() => {
    getUserList();
  }, [getUserList]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setUserIds(newSelectedRowKeys as string[]);
  };
  const rowSelection: TableRowSelection<User.Row> = {
    selectedRowKeys: userIds,
    onChange: onSelectChange,
  };

  const columns: TableProps<User.Row>["columns"] = [
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      width: 60,
      align: "center",
      fixed: true,
      render: (_, { avatar }) => (
        <>
          {avatar && (
            <Avatar size={35} src={<img src={avatar} alt="avatar" />} />
          )}
        </>
      ),
    },
    {
      title: "昵称",
      key: "nickName",
      dataIndex: "nickName",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "用户名",
      key: "userName",
      dataIndex: "userName",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "邮箱",
      key: "email",
      dataIndex: "email",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "手机号",
      key: "phonenumber",
      dataIndex: "phonenumber",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "性别",
      key: "sex",
      dataIndex: "sex",
      ellipsis: true,
      width: 180,
      align: "center",
      render: (_, { sex }) => (
        <>{{ 0: "男", 1: "女", 2: "未知" }[String(sex)]}</>
      ),
    },
  ];
  return (
    <Modal
      width="90vw"
      title={`${props.roleName}-授权用户`}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <div className="page__wrap--g">
        <div className="form__wrap--g">
          <QueryForm
            onChange={(form: User.Query) => {
              setPagination({
                ...pagination,
                pageNo: 1,
              });
              setSearchForm(form);
            }}
          />
        </div>
        <div className="table__wrap--g">
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={tableData}
            rowKey="id"
            loading={loading}
            size="small"
            sticky
            bordered
            scroll={{ x: 1300 }}
            pagination={false}
          />
        </div>
        <div className="pagination__wrap--g">
          <Pagination
            pageSize={pagination.pageSize}
            current={pagination.pageNo}
            total={pagination.total}
            showQuickJumper={true}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              setPagination({
                total: pagination.total,
                pageNo: page,
                pageSize: size,
              });
            }}
          />
        </div>
      </div>
    </Modal>
  );
}
